package com.fatkun;

/**
 * 在GAE上抓取网址
 * @author Fatkun
 * @site http://fatkun.com
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import javax.servlet.http.*;

import java.util.List;
import java.util.Properties;

import javax.jdo.PersistenceManager;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@SuppressWarnings("serial")
public class URL2Servlet extends HttpServlet {
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain; charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");
		URL url = new URL(
				"http://www.google.com/ig/api?weather=TianJin&hl=zh-cn");

		// 读取源码
		BufferedReader reader = new BufferedReader(new InputStreamReader(url
				.openStream(), "gb2312"));
		String line;
		StringBuffer sb = new StringBuffer();
		double fCurPrice = 0;
  		while ((line = reader.readLine()) != null) {
			sb.append(line).append("\n");
		}
		reader.close();
//		int n1 = sb.indexOf("买入价");
//		int n2 = sb.indexOf("卖出价");
//		fCurPrice = Double.valueOf(sb.substring(n1+4,n2-1));
//		
//		n1 = sb.indexOf("最高价");
//		n2 = sb.indexOf("最低价");

		// 输出在网页上
		//resp.getWriter().println(sb.toString());
		// 发送邮件
		// if (fFlag) {
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);

		// String msgBody = "...";

		try {
			// read each person's info and compare,then send one by one
			PersistenceManager pm = PMF.get().getPersistenceManager();
			String query = "select from " + UserData.class.getName();
			List<UserData> userdatas = (List<UserData>) pm.newQuery(query)
					.execute();
			if (userdatas.isEmpty()) {
				// No one
			} else {
				Message msg = new MimeMessage(session);
				msg.setFrom(new InternetAddress("liyun8552@gmail.com",
				"Admin"));
				for (UserData u : userdatas) {			
											
					msg.addRecipients(Message.RecipientType.TO,InternetAddress.parse(u.getUserEmail()));
				}
				
				msg.setSubject(Double.toString(fCurPrice));
				msg.setText("");
				msg.setReplyTo(InternetAddress.parse("hi@huangjinbb.appspotmail.com"));
				Transport.send(msg);
			}
			pm.close();

		} catch (AddressException e) {
			// ...
		} catch (MessagingException e) {
			// ...
			// }
		}
	}
}
